import Vue from 'vue';
import IP from './ipconf'
import {
  getDianZhaoDianPai
} from '../utils/api'
import overlay from '../components/module/overlay';
import overlayVideo from '../components/module/overlayVideo';
let OverlayConstructor = Vue.extend(overlay);
let OverlayVideoConstructor = Vue.extend(overlayVideo);
export default {
  /***影像地址 */
  imageryUrl: IP.gisurl + "gisserver/tmsserver/hpdt1020_02",

  /***白膜地址 */
  bmxpUrl: IP.gisurl + "gisserver/wfsserver/yuyuanjd",

  /**gisserver地址 */
  gissUrl: IP.gisurl,

  /**街道白膜边界线网格名数据存储 */
  bmdata: [],
  wgpoint: [],
  wgline: [],

  /***poi动效存储 */
  beforeImage: {},
  beforeImagescale: {},
  beforeImagetype: '',

  /****视角 */
  setView(webSdk, obj) {
    if (obj.type == "flyto") {
      let camera = webSdk.coreMap.camera;
      webSdk.camera.flyTo(obj.value[0], obj.value[1], obj.value[2], obj.value[3], obj.value[4], obj.value[5], obj.value[6]);
    } else if (obj.type == "set") {
      let camera = webSdk.coreMap.camera;
      camera.setView(obj.value);
    } else if (obj.type == "flytoEntity") {
      let _position = typeof obj.value.position.getValue === 'function' ? obj.value.position.getValue() : obj.value.position;
      let jl = Geoworld.Cartesian3.distance(webSdk.coreMap.camera.position, _position);
      let heading = webSdk.coreMap.camera.heading;
      let pitch = webSdk.coreMap.camera.pitch;
      let options = {
        duration: 1,
        offset: new Geoworld.HeadingPitchRange(heading, pitch, jl)
      };
      webSdk.userScene.flyTo(obj.value, options);
    } else if (obj.type == "flytoWall") {
      let heading = webSdk.coreMap.camera.heading;
      let pitch = webSdk.coreMap.camera.pitch;
      let options = {
        duration: 1,
        offset: new Geoworld.HeadingPitchRange(heading, pitch, 2000)
      };
      webSdk.userScene.flyTo(obj.value, options);
    } else if (obj.type == "flytopolygon") {
      let heading = webSdk.coreMap.camera.heading;
      let pitch = webSdk.coreMap.camera.pitch;
      let options = {
        duration: 1,
        offset: new Geoworld.HeadingPitchRange(heading, pitch, 500)
      };
      webSdk.userScene.flyTo(obj.value, options);
    } else if (obj.type == "flytobillboard") {
      let heading = webSdk.coreMap.camera.heading;
      let pitch = webSdk.coreMap.camera.pitch;
      let options = {
        duration: 1,
        offset: new Geoworld.HeadingPitchRange(heading, pitch, obj.height)
      };
      webSdk.userScene.flyTo(obj.value, options);
    }
  },

  /**白膜加载 */
  addBmLayer(webSdk, obj) {
    let featues = new Geoworld.FeatureJsonData(webSdk, obj);
    return featues;
  },

  /**添加点 */
  addLabel(webSdk, obj) {
    let textFont = obj.font;
    let param = {
      name: obj.name,
      id: webSdk.factory.createUUID(),
      font: 'normal ' + textFont + 'px simSun',
      fillColor: obj.fillColor,
      outlineWidth: obj.outlineWidth,
      outlineColor: obj.outlineColor,
      lon: 0,
      lat: 0,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      distanceDisplayCondition: obj.distanceDisplayCondition,
      alt: 10
    };
    let _arr = [];
    for (let i = 0; i < obj.points.length; i++) {
      param.text = obj.pointsName[i];
      param.lon = obj.points[i][0];
      param.lat = obj.points[i][1];
      let label = webSdk.factory.createLabel(param);
      _arr.push(label)
    }
    return _arr
  },

  /**居委数据加载面 */
  Create_3DPloygon(webSdk, posi, url, colorList, _obj, cb) {
    Geoworld.Math.setRandomNumberSeed(0); //设置随机数种子
    let promise = Geoworld.GeoJsonDataSource.load(url); //geojson面数据
    promise.then(function (dataSource) {
      webSdk.dataSources.add(dataSource);
      let entities = dataSource.entities.values;
      let labelarr = [];
      for (let i = 0; i < entities.length; i++) {
        let entity = entities[i];
        entity.polygon.fill = false;
        //entity.polygon.material = Geoworld.Color.fromCssColorString(colorList[i]);
        entity.polygon.outline = true;
        entity.polygon.outlineWidth = 4 * tedp.mult
        entity.polyline = {
          positions: entity.polygon.hierarchy._value.positions,
          width: entity.polygon.outlineWidth,
          material: Geoworld.Color.YELLOW
        }
        let streetpositions = [];
        for (let key in posi) {
          if (entity.properties._JWMC._value === key) {
            if (key === '丹马居委') {
              streetpositions = [121.487257, 31.228777]
            } else {
              streetpositions = posi[key];
            }

            break
          }
        }

        let param = {
          name: "文字",
          id: webSdk.factory.createUUID(),
          text: entity.properties._JWMC._value,
          font: 'bold ' + 15 * tedp.mult + 'px simSun',
          fillColor: Geoworld.Color.WHITE,
          outlineColor: Geoworld.Color.WHITE,
          outlineWidth: 2,
          lon: streetpositions[0],
          lat: streetpositions[1],
          disableDepthTestDistance: 1000000
        };
        let label = webSdk.factory.createLabel(param);
        labelarr.push(label)
      }
      cb && typeof cb === 'function' ? cb(labelarr) : ''
    });
  },

  /**白膜显示隐藏 */
  showOrfalseBm(flag) {
    for (let i = 0; i < this.bmdata.length; i++) {
      let enyt = this.bmdata[i];
      for (let j = 0; j < enyt.primitive.length; j++) {
        let primitive = enyt.primitive[j];
        primitive.show = flag;
      }
    }
    for (let i = 0; i < this.wgline.length; i++) {
      this.wgline[i].show = flag;
    }
    for (let i = 0; i < this.wgpoint.length; i++) {
      this.wgpoint[i].show = flag;
    }
  },

  /**不同类型撒点 */
  mapLayersCountArr: [],
  mapLayersArr: [],
  addpoint(webSdk, type, point, lngkey, latkey) {
    let img = './static/layers/' + type + '.png';
    let index = $.inArray(type, this.mapLayersArr);
    let _index = 1;
    if (index >= 0) {
      _index = this.mapLayersCountArr[index] + 1;
    }


    let position = ''
    if (point[lngkey] && point[latkey]) {
      position = Geoworld.Cartesian3.fromDegrees(parseFloat(point[lngkey]), parseFloat(point[latkey]), 3);
    }
    let billboard = {
      type: "billboard",
      value: {
        id: type + _index,
        position: position,
        billboard: {
          image: img,
          width: 15 * tedp.mult,
          height: 15 * tedp.mult,
          disableDepthTestDistance: 1000000,
        },
        description: point
      }
    };
    let model = this.addEntity(webSdk, billboard);
    // 添加图标  png
    if (index >= 0) {
      this.mapLayersCountArr[index]++;
    } else {
      this.mapLayersArr.push(type);
      this.mapLayersCountArr.push(1);
    }
    return model;
  },

  /***添加entity */
  addEntity(webSdk, obj) {
    let layer;
    if (obj.type == "point") {
      layer = webSdk.factory.createPoint(obj.value);
    } else if (obj.type == "billboard") {
      layer = webSdk.entities.add(obj.value);
    } else if (obj.type == "label") {
      layer = webSdk.factory.createLabel(obj.value);
    } else if (obj.type == "polyline") {
      layer = webSdk.factory.createPolyline(obj.value);
    } else if (obj.type == "polylineVolume") {
      layer = webSdk.factory.createPolylineVolume(obj.value);
    } else if (obj.type == "corridor") {
      layer = webSdk.factory.createCorridor(obj.value);
    } else if (obj.type == "wall") {
      layer = webSdk.factory.createWall(obj.value);
    } else if (obj.type == "polygon") {
      layer = webSdk.factory.createPolygon(obj.value);
    } else if (obj.type == "box") {
      layer = webSdk.factory.createBox(obj.value);
    } else if (obj.type == "rectangle") {
      layer = webSdk.factory.createRectangle(obj.value);
    } else if (obj.type == "ellipse") {
      layer = webSdk.factory.createEllipse(obj.value);
    } else if (obj.type == "cylinder") {
      layer = webSdk.factory.createCylinder(obj.value);
    } else if (obj.type == "ellipsoid") {
      layer = webSdk.factory.createEllipsoid(obj.value);
    }
    return layer;
  },

  /**鼠标左键点击触发 */
  mapLeftClick(webSdk) {
    let scene = webSdk.coreMap.scene;
    let handler = new Geoworld.ScreenSpaceEventHandler(scene.canvas);
    let me = this;
    handler.setInputAction(function (e) {

      let pick = scene.pick(e.position);
      if (!pick) return;

      //目前存在entity和primitive来创建图标点两种方式 需要进行判断
      let _pickObj = typeof pick.id === 'object' ? pick.id : pick.primitive;
      if (!_pickObj) return;

      let pickpose = scene.globe.ellipsoid.cartesianToCartographic(pick.id.position && pick.id.position._value);
      let Geography = [Geoworld.Math.toDegrees(pickpose.longitude), Geoworld.Math.toDegrees(pickpose.latitude), pickpose.height];

      //poi动效
      me.clearPointDx();
      me.addPointDx(pick);
      let type = _pickObj._description._value.layerType;
      //视频
      if (type === 'video') {
        let flyobj = {
          type: "flytoEntity",
          value: _pickObj
        }
        me.setView(webSdk, flyobj);
        me.htmls(webSdk, {
          url: _pickObj._description._value.video_device_coding,
          title: _pickObj._description._value.video_name
        }, Geography, 0)
      }
      //店招店牌
      else if (type === 'dzdp') {
        let dzdpId = _pickObj._description._value.id;
        getDianZhaoDianPai(JSON.stringify({
          id: dzdpId
        })).then(res => {
          if (res.status === 200) {
            let flyobj = {
              type: "flytoEntity",
              value: _pickObj
            }
            me.setView(webSdk, flyobj);
            me.htmls(webSdk, {
              pdata: res.data.data.DianZhaoDianPaiInfo,
              type: 'dzdp'
            }, Geography, 1)
          }
        })
      }



    }, Geoworld.ScreenSpaceEventType.LEFT_CLICK);
  },

  /**添加poi动效 */
  addPointDx(pick) {
    let _pickObj = typeof pick.id === 'object' ? pick.id : pick.primitive;
    if (pick.id.id) {
      if (this.beforeImage && this.beforeImagescale.billboard) {
        window.clearInterval(this.beforeImage);
        this.beforeImagescale.billboard.scale = 1;
      }
      let index = 1,
        scale = 0.5;
      _pickObj.imageClock = setInterval(function () {
        if (_pickObj != null && _pickObj.billboard) {
          scale += 1.2;
          _pickObj.billboard.image = _pickObj.billboard.image._value;
          index += 1;
          _pickObj.billboard.scale = scale;

          if (index > 3) {
            index = 1;
          }
          if (scale > 2.3) {
            scale = 0.5
          }
        }
      }, 600);
      //设置变量记录之前点击的图标
      this.beforeImage = _pickObj.imageClock;
      this.beforeImagescale = _pickObj;
      this.beforeImagetype = 'entity'
    } else {
      if (beforeImage) {
        window.clearInterval(beforeImage);
        beforeImagescale.scale = 1;
      }
      let index = 1,
        scale = 0.5;
      pick.primitive.pickPrimitive.imageClock = setInterval(function () {
        if (pick.primitive.pickPrimitive != null) {
          scale += 1.2;
          pick.primitive.pickPrimitive.image = pick.primitive.pickPrimitive.image;
          index += 1;
          pick.primitive.pickPrimitive.scale = scale;

          if (index > 3) {
            index = 1;
          }
          if (scale > 2.3) {
            scale = 0.5
          }
        }
      }, 600);
      //设置变量记录之前点击的图标
      this.beforeImage = pick.primitive.pickPrimitive.imageClock;
      this.beforeImagescale = pick.primitive.pickPrimitive;
      this.beforeImagetype = 'entity'
    }
  },

  /**清除poi动效 */
  clearPointDx() {
    //entity
    if (this.beforeImage && this.beforeImagetype == 'entity') {
      window.clearInterval(this.beforeImage);
      this.beforeImagescale.billboard.scale._value = 1;
    }
    //primitive
    if (this.beforeImage && this.beforeImagetype == 'primitive') {
      window.clearInterval(Global.beforeImage);
      this.beforeImagescale.scale = 1;
    }

  },

  /**poi弹窗跟随 
   * type 0.视频弹窗 or 1.普通弹窗 
   */
  htmls(webSdk, options, Geography, type) {
    if (document.getElementById('overlay')) {
      document.getElementById('overlay').remove()
    }
    let instance = null;
    if (type === 1) {
      instance = new OverlayConstructor({
        data: options
      });
    } else if (type === 0) {
      instance = new OverlayVideoConstructor({
        data: options
      });
    }
    if (!instance) return;

    instance.$mount();
    instance.show = true;
    document.getElementsByClassName('te-module')[0].appendChild(instance.$el);
    new this.addOverlays({
      element: instance,
      offset: {
        x: 0,
        y: (type === 1 ? 0 : -432 * tedp.mult)
      },
      viewer: webSdk.coreMap,
      _worldPosition: Geography
    });
  },

  /** */
  addOverlays(opt) {
    opt = opt || {};
    let _self = this;
    /**
     * @type {string|number} overlay id
     */
    this.id = opt.id;
    /**
     * @type {document.element} overlay的内容元素
     */
    this.element = opt.element;
    /**
     * @type {Array} 保存Popup框的x,y坐标
     */
    this.position = opt.position;

    this._worldPosition = opt._worldPosition;
    /**
     * @type {*} popup框相对于原点偏移像素值
     */
    this.offset = opt.offset;
    /**
     * @type {Cesium.Cartesian2}
     */
    this.scratch = new Geoworld.Cartesian2();
    /**
     *
     * @type {Cesium.Viewer}
     * @private
     */
    this._viewer = opt.viewer;
    /**
     * 设置关联的cesium viewer
     * @param viewer
     */
    _self._viewer.scene.preRender.addEventListener(function () {
      if (_self.element.show) {
        _self.update()
      }
    });
    /**
     * 获取关联的cesium viewer
     * @return {Cesium.Viewer}
     */
    this.getViewer = function () {
      return this._viewer;
    };
    /**
     * 设置位置
     * @param position{Array}
     */
    this.setPosition = function (position) {
      if (!position) {
        _self.close();
        return;
      }
      if (position instanceof Array) {
        position[0] = position[0] || 0;
        position[1] = position[1] || 0;
        position[2] = position[2] || 0;
        position = Geoworld.Cartesian3.fromDegrees(position[0], position[1], position[2]);
      }
      if (!_self.getViewer()) {
        return;
      }
      let canvasPosition = Geoworld.SceneTransforms.wgs84ToWindowCoordinates(_self.getViewer().scene, position);
      if (Geoworld.defined(canvasPosition)) {
        _self.element.style = {
          top: (canvasPosition.y + _self.offset.y) / tedp.mult + 'px',
          left: (canvasPosition.x + _self.offset.x) / tedp.mult + 'px'
        }
        _self.element.show = true
      }
      _self._worldPosition = position;
    };
    this.update = function () {
      this.setPosition(this._worldPosition);
    };
    /**
     *
     * @return {Array}
     */
    this.getPosition = function () {
      return _self.position;
    };
    this.close = function () {
      _self.element.show = false;
    };
    this.show = function () {
      _self.element.show = true;
    };
  },
  /***清除poi */
  removePoi(webSdk, type) {
    let index = $.inArray(type, this.mapLayersArr);
    let length = this.mapLayersCountArr[index];
    if (length == undefined || length <= 0) {
      return;
    }
    for (let i = 1; i <= length; i++) {
      webSdk.entities.removeById(type + i);
    }
    this.mapLayersArr.splice(index, 1);
    this.mapLayersCountArr.splice(index, 1);
    if (document.getElementById('overlay')) {
      document.getElementById('overlay').remove()
    }
  },

  /**点位聚合 */
  PolymerizaCon: {},
  customentity: {},
  pointPolymeriza(webSdk, type, points, lngkey, latkey) {
    //聚合
    let entity = webSdk.factory.createFeatureLayer({
      sourceType: "custom"
    });
    this.customentity[type] = entity;
    this.PolymerizaCon[type] = webSdk.coreMap.scene.primitives.add(new Geoworld.PointPrimitiveCollection());
    for (let i = 0; i < points.length; i++) {

      this.PolymerizaCon[type].add({
        position: Geoworld.Cartesian3.fromDegrees(points[i][lngkey], points[i][latkey], 3),
        color: Geoworld.Color.fromCssColorString("#1afa29"),
        outlineColor: Geoworld.Color.fromCssColorString("#1afa29"),
        outlineWidth: 1 * tedp.mult,
        pixelSize: 2,
        show: true,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        distanceDisplayCondition: new Geoworld.DistanceDisplayCondition(
          1001
        ),
        id: type
      })
      let model = this.pointAggregation(entity, type, points[i], lngkey, latkey);
      points[i].modelId = model._id;
      points[i].layerType = type;
    }

  },
  pointAggregation(entity, type, point, lngkey, latkey) {
    let img = './static/layers/' + type + '.png';

    let index = $.inArray(type, this.mapLayersArr);
    let _index = 1;
    if (index >= 0) {
      _index = this.mapLayersCountArr[index] + 1;
    }
    let position = Geoworld.Cartesian3.fromDegrees(parseFloat(point[lngkey]), parseFloat(point[latkey]), 3);
    let obj = {
      id: type + _index,
      position: position,
      billboard: {
        image: img,
        width: 40 * tedp.mult,
        height: 40 * tedp.mult,
        disableDepthTestDistance: 1000000,
        distanceDisplayCondition: new Geoworld.DistanceDisplayCondition(10.0, 1000.0)
      },
      popup: {
        html: "",
        anchor: [0, -25]
      },
      description: point
    }
    let model = entity.entities.add(obj);
    // 添加图标  png
    if (index >= 0) {
      this.mapLayersCountArr[index]++;
    } else {
      this.mapLayersArr.push(type);
      this.mapLayersCountArr.push(1);
    }
    return model;
  },

  /**清除聚合点位 */
  clearpointPolymeriza(type) {
    if (this.PolymerizaCon[type]) {
      for (let i = 0; i < this.PolymerizaCon[type]._pointPrimitives.length; i++) {
        this.PolymerizaCon[type]._pointPrimitives[i].show = false;
      }
    }
    if (this.customentity[type]) {
      this.customentity[type].show = false
    }
  },

  /**视角还原 */
  reductView(webSdk) {
    let obj = {
      type: "flyto",
      value: [121.4835510617256, 31.190779812434663, 2746.137627851429, 1.3463831619755644, -33.63531007682243, 0.004813942313900209, 0.5]
    };
    this.setView(webSdk, obj);
  }
}
